package it.orma.iridehr.jobs;

import it.orma.iridehr.controllers.ricerca.RicercaForm;
import it.orma.iridehr.entities.CVCandidato;
import it.orma.iridehr.entities.DatiGenerali;
import it.orma.iridehr.entities.News;
import it.orma.iridehr.entities.Opportunita;
import it.orma.iridehr.entities.SchedaCandidato;
import it.orma.iridehr.repository.CandidatoRepository;
import it.orma.iridehr.repository.NewsRepository;
import it.orma.iridehr.repository.ParametriRepository;
import it.orma.iridehr.repository.RicercaRepository;
import it.orma.iridehr.repository.ricercaOpportunita.RicercaOpportunitaRepository;
import it.orma.iridehr.service.AlfrescoService;
import it.orma.iridehr.service.EmailService;
import it.orma.iridehr.services.helper.RisultatoRicerca;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.AndTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.SearchTerm;

import org.alfresco.cmis.client.AlfrescoDocument;
import org.alfresco.cmis.client.AlfrescoFolder;
import org.alfresco.webservice.util.ISO9075;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.ItemIterable;
import org.apache.chemistry.opencmis.client.api.OperationContext;
import org.apache.chemistry.opencmis.client.api.QueryResult;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.DocumentImpl;
import org.apache.chemistry.opencmis.client.runtime.OperationContextImpl;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.data.ContentStream;
import org.apache.chemistry.opencmis.commons.data.PropertyData;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.sun.mail.imap.IMAPBodyPart;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;

public class EmailTask {
	
	private Integer messageWindow;
	
	@Autowired 
	AlfrescoService alfrescoService;
	
	@Autowired 
	EmailService emailService;
	
	@Autowired
	CandidatoRepository candidatoRepository;
	
	@Autowired
	NewsRepository newsRepository;
	
	@Autowired
	private RicercaRepository ricercaRepository;
	
	@Autowired
	ParametriRepository parametriRepository;
	
	@Autowired
	private RicercaOpportunitaRepository ricercaOpportunitaRepository;

	public Integer getMessageWindow() {
		return messageWindow;
	}

	public void setMessageWindow(Integer messageWindow) {
		this.messageWindow = messageWindow;
	}
	
	public static EmailTask createTask() throws Exception {
	    
		EmailTask rmt = new EmailTask();
		rmt.setMessageWindow(5);
		
	    return rmt;
	}
	
	
	public void fetchEmail() throws IOException {
		
	    Properties properties = new Properties();
	    String port = "993";
	    String host = "imap.gmail.com"; 
        String userName = "orma.adm@gmail.com";
        String password = "JomrARZQGuhK3TSXQ5Fd";
        InputStream is = null;		   
        String opp = null;
		String email = null;
        String extension = null;
        byte[] bytes=null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        properties.put("mail.imap.host", host);
        properties.put("mail.imap.port", port);
        properties.put("mail.imap.auth","true");
        properties.setProperty("mail.imap.ssl.enable", "true");
        properties.setProperty("mail.imap.socketFactory.fallback", "false");
        properties.setProperty("mail.imap.socketFactory.port",
                String.valueOf(port));
        javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);
        session.setDebug(true);
        try {
        	System.out.println("Collegamento al server mail "+host);
            // connects to the message store
        	javax.mail.Store store = session.getStore("imap");
            store.connect(userName, password);
            System.out.println("Fatto");
            // opens the inbox folder
            javax.mail.Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(javax.mail.Folder.READ_WRITE);
            System.out.println("Recupero nuovi messaggi...");
            // fetches new messages from server
            Flags seen = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
         // creates a search criterion
           
            SearchTerm searchCondition = new SearchTerm() {
                @Override
                public boolean match(Message message) {
                    try {
                    	
                    	String PATTERN = "^[A-Za-z]{1,2}[0-9]{4,6}\\s*[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
                    	Pattern pattern = 
                        Pattern.compile(PATTERN);

                        Matcher matcher = pattern.matcher(message.getSubject());
                    	if (matcher.matches())
                            return true;
                    } catch (MessagingException ex) {
                        ex.printStackTrace();
                    }
                    return false;
                }
                
            };
            
            SearchTerm searchTerm = new AndTerm(unseenFlagTerm, searchCondition);
            
            Message[] notFiltered = folderInbox.getMessages(folderInbox.getMessageCount()-1, folderInbox.getMessageCount());            
            Message[] arrayMessages = folderInbox.search(searchTerm,notFiltered);
            System.out.println("Recuperati "+arrayMessages.length+ " nuovi messaggi...");
 
            //for (int i = 0; i < arrayMessages.length; i++) {
            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
               
                message.setFlag(Flags.Flag.SEEN, true);
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();
                String receivedDate = message.getReceivedDate().toString();
                String contentType = message.getContentType();
                String messageContent = "";
 
                // store attachment file name, separated by comma
                String attachFiles = "";
 
                if (contentType.contains("multipart")) {
                    // content may contain attachments
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // this part is attachment
                        	Calendar c = Calendar.getInstance();
                        	c.setTime(message.getReceivedDate());
                            String fileName = "CV_"+message.getSubject().substring(0,message.getSubject().indexOf(" "))+"_"+message.getSubject().substring(message.getSubject().lastIndexOf(" "));
                           //Guid_Anno_Mese_Giorno_NomeFile
                            
                            attachFiles += part.getFileName() + ", ";
                            //System.out.println("Il messaggio contiene un allegato lo salvo come "+saveDirectory + File.separator + fileName);
                            //part.saveFile(saveDirectory + File.separator + fileName);
                            //System.out.println("Fatto");
                            is = part.getInputStream();
                            opp = message.getSubject().substring(0,message.getSubject().indexOf(" "));
                            email = message.getSubject().substring(message.getSubject().lastIndexOf(" "));
                            extension = part.getContentType();
                            //DataInputStream dis = new DataInputStream(is);
                            byte[] buffer = new byte[4096];
                            int byteRead;
                            while ((byteRead = is.read(buffer)) != -1) {
                                baos.write(buffer, 0, byteRead);
                            }
                			//dis.readFully(bytes);
                            System.out.println("extension:"+extension);
                            is.close();
                        } else {
                            // this part may be the message content
                            messageContent = part.getContent().toString();
                        }
                    }
 
                    if (attachFiles.length() > 1) {
                        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                    }
                } else if (contentType.contains("text/plain")
                        || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }
 
                // print out details of each message
                System.out.println("Message #" + (i + 1) + ":");
                System.out.println("\t From: " + from);
                System.out.println("\t Subject: " + subject);
                System.out.println("\t Sent Date: " + sentDate);
                System.out.println("\t Received Date: " + receivedDate);
                System.out.println("\t Message: " + messageContent);
                System.out.println("\t Attachments: " + attachFiles);
                
            }
            //TODO:storeCV(is,opp,email,extension,baos);
            // disconnect
            folderInbox.close(false);
            store.close();
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for imap.");
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

	}
	
	public void fetchNewEMail() {
		
	    Properties properties = new Properties();

	    String port = "143";
        String host = "server.orma.ws";
        String userName = "cvalfresco@orma.ws";
        String password = "Dpr720deb";

        properties.put("mail.imap.host", host);
        properties.put("mail.imap.port", port);
        properties.put("mail.imap.auth","true");
        properties.setProperty("mail.imap.ssl.enable", "false");
        properties.setProperty("mail.imap.socketFactory.fallback", "false");
        properties.setProperty("mail.imap.socketFactory.port",
                String.valueOf(port));
        javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);
        //session.setDebug(true);
        try {
        	System.out.println("Collegamento al server mail "+host);
            // connects to the message store
        	javax.mail.Store store = session.getStore("imap");
            store.connect(userName, password);
            System.out.println("Fatto");
            // opens the inbox folder
            IMAPFolder folderInbox = (IMAPFolder) store.getFolder("INBOX");
            folderInbox.open(javax.mail.Folder.READ_WRITE);
            System.out.println("Recupero nuovi messaggi...");
            // fetches new messages from server
            Flags seen = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
         // creates a search criterion
            
            SearchTerm searchCondition = new SearchTerm() {
                @Override
                public boolean match(Message message) {
                    try {
                    	
                    	String PATTERN = "^[A-Za-z]{1,2}[0-9]{4,6}\\s*[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
                    	Pattern pattern = 
                        Pattern.compile(PATTERN);

                        Matcher matcher = pattern.matcher(message.getSubject());
                    	if (matcher.matches())
                            return true;
                    } catch (MessagingException ex) {
                        ex.printStackTrace();
                    }
                    return false;
                }
                
            };
            
            Message msg = null;  
            
            SearchTerm searchTerm = new AndTerm(unseenFlagTerm, searchCondition);
            
            int messageCount = folderInbox.getUnreadMessageCount();
            int lowerLimit = 1000;
            lowerLimit = Integer.parseInt(parametriRepository.ricercaParametro("EMAIL_LOWEST_UID"));
            Message[] arrayMessages0=null;
            if(messageCount>0){
            	long counter=1;
            	while (counter<=messageCount&&folderInbox.getUIDNext()-counter>lowerLimit){
            		arrayMessages0 = folderInbox.getMessagesByUID(folderInbox.getUIDNext()-counter, folderInbox.getUIDNext()-counter);
            		System.out.println("counter:"+counter);
            		if (arrayMessages0!=null&&arrayMessages0.length>0&&arrayMessages0[0].getFlags().contains(Flags.Flag.SEEN)||arrayMessages0==null||arrayMessages0!=null&&arrayMessages0.length==0)
            			counter++;
            		if (arrayMessages0!=null&&arrayMessages0.length>0&&!arrayMessages0[0].getFlags().contains(Flags.Flag.SEEN))
            			break;
            	}
            	
            Message[] arrayMessages = new Message[1];
            arrayMessages[0] = arrayMessages0[0];
            System.out.println("Recuperati "+arrayMessages.length+ " nuovi messaggi...");
            
            String PATTERN = "\\s*[A-Za-z]{1}[/\\\\][0-9]{4}";
        	Pattern pattern = Pattern.compile(PATTERN);
           
            
            for (int i = 0; i < arrayMessages.length; i++) {
                          	
            	Message message = arrayMessages[i];
            	System.out.println(message.getSubject());
            	Matcher matcher = pattern.matcher(message.getSubject());
            	InputStream is = null;		   
                String opp = null;
        		String email = null;
        		ArrayList<ByteArrayOutputStream> baoss = new ArrayList<ByteArrayOutputStream>();
        	    ArrayList<String> extensions = new ArrayList<String>();
        	    ArrayList<String> names = new ArrayList<String>();
        	    
                byte[] bytes=null;
            	if (matcher.find()) {
                   int startIndex= matcher.start();
                   int endIndex =  matcher.end();
                   
                   String oppTmp = message.getSubject().substring(startIndex,endIndex).trim();
                   opp = oppTmp.substring(0,1)+oppTmp.substring(2);  
                   
	                message.setFlag(Flags.Flag.SEEN, true);
	                Address[] fromAddress = message.getFrom();
	                String from = fromAddress[0].toString();
	                String subject = message.getSubject();
	                String sentDate = message.getSentDate().toString();
	                String receivedDate = message.getReceivedDate().toString();
	                String contentType = message.getContentType();
	                String messageContent = message.getContent().toString();
	                
	                String attachFiles = "";
	 
	                if (contentType.contains("multipart")) {
	                    // content may contain attachments
	                    Multipart multiPart = (Multipart) message.getContent();
	                    int numberOfParts = multiPart.getCount();
	                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
	                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
	                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {                       	
	                        	String extension = part.getFileName().substring(part.getFileName().lastIndexOf(".")+1).toLowerCase();                       	
	                        	if (extension.indexOf("pdf")>-1||extension.indexOf("doc")>-1){
		                        	
		                           
		                        	Calendar c = Calendar.getInstance();
		                        	c.setTime(message.getReceivedDate());
		                           
		                            attachFiles += part.getFileName() + ", ";
		                            
		                            is = part.getInputStream();
		                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
		                            byte[] buffer = new byte[4096];
		                            int byteRead;
		                            while ((byteRead = is.read(buffer)) != -1) {
		                                baos.write(buffer, 0, byteRead);
		                            }
		                		
		                            System.out.println("extension:"+extension);
		                            baoss.add(baos);
		                            extensions.add(extension);
		                            names.add(part.getFileName());
		                            is.close();
	                        	}else if(extension.indexOf("html")>-1){
	                        		IMAPBodyPart ibp = (IMAPBodyPart)part;
		                        	if(ibp.getContentType().indexOf("html")>-1){
		                        		String mmp = ((String)((Multipart)message.getContent()).getBodyPart(partCount).getContent());
			                            
			                            BufferedReader br = new BufferedReader(new StringReader(mmp));
			                            String line = null;
			                            String emailRegex = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
			                            Pattern pat = Pattern.compile(emailRegex);
			                            boolean flagMittente=false;
			                            while ((line = br.readLine())!=null){
			                            	if (line.indexOf("Mittente")>-1){
			                            		flagMittente=true;
			                            	}
			                            	if (flagMittente==true){
			                            		Matcher matcher0 = pat.matcher(line);
			                            		if (matcher0.find()){
			                            			int start = matcher0.start();
			                            			int end = matcher0.end();
			                            			email = line.substring(start,end).replaceAll("&lt;","").replaceAll("&gt;","").trim();
			                            			System.out.println(email);
			                            			break;
			                            		}
			                            	}
			                            }
		                        	}
	                        	}
	                        } else {
	                            // this part may be the message content
	                        	IMAPBodyPart ibp = (IMAPBodyPart)part;
	                        	if(ibp.getContentType().indexOf("html")>-1){
		                        	MimeMultipart mmp = ((MimeMultipart)((MimeMultipart)message.getContent()).getBodyPart(partCount).getContent());
		                            
		                            BufferedReader br = new BufferedReader(new StringReader(mmp.getBodyPart(1).getContent().toString()));
		                            String line = null;
		                            String emailRegex = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
		                            Pattern pat = Pattern.compile(emailRegex);
		                            boolean flagMittente=false;
		                            while ((line = br.readLine())!=null){
		                            	if (line.indexOf("Mittente")>-1){
		                            		flagMittente=true;
		                            	}
		                            	if (flagMittente==true){
		                            		Matcher matcher0 = pat.matcher(line);
		                            		if (matcher0.find()){
		                            			int start = matcher0.start();
		                            			int end = matcher0.end();
		                            			email = line.substring(start,end).replaceAll("&lt;","").replaceAll("&gt;","").trim();
		                            			System.out.println("not attachment:"+email);
		                            			break;
		                            		}
		                            	}
		                            }
	                        	}else if (ibp.getContentType().indexOf("multipart")>-1){
	                        		int numberOfPartsIn = ((MimeMultipart)part.getContent()).getCount();
	                        		for (int partCountIn = 0; partCountIn < numberOfPartsIn; partCountIn++) {
	                        			if(((MimeMultipart)part.getContent()).getBodyPart(partCountIn).getContentType().indexOf("html")>-1){
	                        				String mmp = (String)(((MimeMultipart)part.getContent()).getBodyPart(partCountIn).getContent());
				                            
				                            BufferedReader br = new BufferedReader(new StringReader(mmp));
				                            String line = null;
				                            String emailRegex = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
				                            Pattern pat = Pattern.compile(emailRegex);
				                            boolean flagMittente=false;
				                            while ((line = br.readLine())!=null){
				                            	if (line.indexOf("Mittente")>-1){
				                            		flagMittente=true;
				                            	}
				                            	if (flagMittente==true){
				                            		Matcher matcher0 = pat.matcher(line);
				                            		if (matcher0.find()){
				                            			int start = matcher0.start();
				                            			int end = matcher0.end();
				                            			email = line.substring(start,end).replaceAll("&lt;","").replaceAll("&gt;","").trim();
				                            			System.out.println(email);
				                            			break;
				                            		}
				                            	}
				                            }
	                        			}
	                        		
	                        		}
	                        		
	                        	}
	                        }
	                    }
 
                    if (attachFiles.length() > 1) {
                        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                    }
                } else if (contentType.contains("text/plain")
                        || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }
 
                // print out details of each message
                System.out.println("Message #" + (i + 1) + ":");
                System.out.println("\t From: " + from);
                System.out.println("\t Subject: " + subject);
                System.out.println("\t Sent Date: " + sentDate);
                System.out.println("\t Received Date: " + receivedDate);
                System.out.println("\t Message: " + messageContent);
                System.out.println("\t Attachments: " + attachFiles);
                try{
                	if (email!=null&&baoss.size()>0){
                		System.out.println("CV+Allegati:"+baoss.size());
                		List<Object> res = ricercaRepository.ricercaLinkAlfrescoDB(email);
                		if (res!=null && res.size()>0){
                			storeDocs(is,opp,email,extensions,names,baoss,((BigInteger)res.get(0)).longValue());
                		}else
                			storeDocs(is,opp,email,extensions,names,baoss,null);
	            		handleCandidate(email,opp);
	            		javax.mail.Folder dFolder = store.getFolder("CV");  //CV
		                Message[] msgs = new Message[1];
		                msgs[0] = message;
		                folderInbox.copyMessages(msgs, dFolder);
		                folderInbox.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);
		                folderInbox.expunge();
		                
                	}else{
                		 javax.mail.Folder dFolder = store.getFolder("Altro");  //Altro
       	              	 Message[] msgs = new Message[1];
       	              	 msgs[0] = message;
       	              	 folderInbox.copyMessages(msgs, dFolder);
       	              	 folderInbox.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);
       	              	 folderInbox.expunge();
                	}
            	}catch(Exception e){
            		e.printStackTrace();
            	}
              }else{
            	  javax.mail.Folder dFolder = store.getFolder("Altro"); //Altro
	              Message[] msgs = new Message[1];
	              msgs[0] = message;
	              folderInbox.copyMessages(msgs, dFolder);
	              folderInbox.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);
	              folderInbox.expunge();
              }
            }
            // disconnect
            folderInbox.close(true);
            //folderInbox
            store.close();
            }
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for imap.");
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
	
	}
	
	private void handleCandidate(String email, String opp) {
		
		List<Object> res = ricercaRepository.ricercaLinkAlfrescoDB(email);
		if (res!=null && res.size()>0){
//			Long idCandidato = ((BigInteger) res.get(0)).longValue();
//			List<RisultatoRicerca> ricerca = alfrescoService.ricercaCandidatoSuAlfresco(email,"CV");
//			Iterator<RisultatoRicerca> ricercaIt = ricerca.iterator();
//			while(ricercaIt.hasNext()){
//				CVCandidato doc = new CVCandidato();
//				RisultatoRicerca rRicerca = ricercaIt.next();
//				doc.setIdAlfresco(rRicerca.getIdDocumento());
//				doc.setTipo("CV");
//				doc.setNome(rRicerca.getDettaglio());
//				doc.setEstensione(rRicerca.getDettaglio().substring(rRicerca.getDettaglio().lastIndexOf(".")));
//				doc.setTitolo(rRicerca.getTitle());
//				doc.setIdCandidato(idCandidato);
// 				if(candidatoRepository.salvaLinkAlfrescoIfNotExists(doc)){
				News news = new News();
				Opportunita opportunita = ricercaOpportunitaRepository.caricaOpportunitaByProgr(Long.parseLong(opp.substring(1)));
				news.setOpportunita(opportunita);
				news.setEmail(email);
				news.setGestito("N");
				news.setMailInviata("N");
				news.setVisibile("S");
				news.setDataCreazione(new Date());
				try{
					newsRepository.insertNewsNoTx(news);
				}catch(Exception e){
					System.out.println("inserimento news non andato a buon fine");
				}
//				}
//			}
//			ricerca = alfrescoService.ricercaCandidatoSuAlfresco(email,"Allegati");
//			ricercaIt = ricerca.iterator();
//			CVCandidato ultimoAll = ricercaRepository.caricaUltimoDocumento(idCandidato, "All");
//	    	Integer nextIndex = 1;
//	    	if (ultimoAll!=null){
//	    		nextIndex = Integer.parseInt(ultimoAll.getTitolo().substring(ultimoAll.getTitolo().lastIndexOf("_")+1))+1;
//	    	}
//			while(ricercaIt.hasNext()){
//				CVCandidato doc = new CVCandidato();
//				RisultatoRicerca rRicerca = ricercaIt.next();
//				doc.setIdAlfresco(rRicerca.getIdDocumento());
//				doc.setTipo("All");
//				doc.setNome(rRicerca.getDettaglio());
//				doc.setEstensione(rRicerca.getDettaglio().substring(rRicerca.getDettaglio().lastIndexOf(".")));
//				doc.setTitolo("All_"+email+"_"+nextIndex);
//				doc.setIdCandidato(idCandidato);
//				candidatoRepository.salvaLinkAlfresco(doc);
//				nextIndex+=1;
//			}
		}else{
			News news = new News();
			Opportunita opportunita = ricercaOpportunitaRepository.caricaOpportunitaByProgr(Long.parseLong(opp.substring(1)));
			news.setOpportunita(opportunita);
			news.setEmail(email);
			news.setGestito("N");
			news.setMailInviata("N");
			news.setVisibile("S");
			news.setDataCreazione(new Date());
			try{
				newsRepository.insertNewsNoTx(news);
			}catch(Exception e){
				System.out.println("inserimento news non andato a buon fine");
			}
		
		}		
			
	}

	
	private void storeDocs(InputStream is,String opp, String email,ArrayList<String> extensions,ArrayList<String> names,
			ArrayList<ByteArrayOutputStream> baoss,Long idScheda) {
		
    	Integer nextIndex = 1;
    	SchedaCandidato schedaCandidato = null;
    	if (idScheda!=null){
    		schedaCandidato = ricercaRepository.caricaSchedaCandidato(idScheda);
    		CVCandidato ultimoAll = ricercaRepository.caricaUltimoDocumento(schedaCandidato.getIdSchedaCandidato(), "CV");
    		if (ultimoAll!=null){
    			nextIndex = Integer.parseInt(ultimoAll.getTitolo().substring(ultimoAll.getTitolo().lastIndexOf("_")+1))+1;
    		}
    	}
    	String title = "CV_"+email+"_"+opp+"_"+(nextIndex); 
		
		String docId = alfrescoService.storeCV(email, extensions.get(0), names.get(0), title, baoss.get(0), "CV");
		if (idScheda!=null){
			CVCandidato doc = new CVCandidato();
	        doc.setDataRicezione(new Date());
	        doc.setIdAlfresco(docId);
	        doc.setIdCandidato(schedaCandidato.getIdSchedaCandidato());
	        doc.setNome(names.get(0));
	        doc.setEstensione(extensions.get(0));
	        doc.setTipo("CV");
	        doc.setTitolo(title);
	        candidatoRepository.salvaLinkAlfrescoNoTx(doc);
		}
		baoss.remove(0);
		extensions.remove(0);
		names.remove(0);
		for(int i =0;i<baoss.size();i++){
			Integer nextIndexAll = 1;
			if (idScheda!=null){
	    		schedaCandidato = ricercaRepository.caricaSchedaCandidato(idScheda);
	    		CVCandidato ultimoAll = ricercaRepository.caricaUltimoDocumento(schedaCandidato.getIdSchedaCandidato(), "All");
	    		if (ultimoAll!=null){
	    			nextIndexAll = Integer.parseInt(ultimoAll.getTitolo().substring(ultimoAll.getTitolo().lastIndexOf("_")+1))+1;
	    		}
	    	}
			String titleAll = "All_"+email+"_"+nextIndexAll; 
			
			String docIdAll = alfrescoService.storeCV(email, extensions.get(i), names.get(i), titleAll, baoss.get(i), "All");
			if (idScheda!=null){
				CVCandidato doc = new CVCandidato();
		        doc.setDataRicezione(new Date());
		        doc.setIdAlfresco(docIdAll);
		        doc.setIdCandidato(schedaCandidato.getIdSchedaCandidato());
		        doc.setNome(names.get(i));
		        doc.setEstensione(extensions.get(i));
		        doc.setTipo("All");
		        doc.setTitolo(titleAll);
		        candidatoRepository.salvaLinkAlfrescoNoTx(doc);
			}
			
		}
		
	}
	
	
//	private void storeDocs(InputStream is,String opp, String email,ArrayList<String> extensions,ArrayList<String> names,
//			ArrayList<ByteArrayOutputStream> baoss) {
//
//		final String sites = "/Sites";
//		
//		// default factory implementation
//		SessionFactory factory = SessionFactoryImpl.newInstance();
//		Map<String,String> parameter = new HashMap<String, String>();
//
//		// user credentials
//		//parameter.put(SessionParameter.USER, "admin");
//		//parameter.put(SessionParameter.PASSWORD, "admin");
//
//		// connection settings
//		parameter.put(SessionParameter.USER, "user");
//		parameter.put(SessionParameter.PASSWORD, "ljeq0AjF0kz36IJfXbci");
//
//		// connection settings
//		parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost:3000/alfresco/service/cmis");
//		parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
//		
//		//parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost:8080/alfresco/service/cmis");
//		parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
//		//parameter.put(SessionParameter.REPOSITORY_ID, "d88d6ab2-1d08-4e49-954d-1a221532ff2f");
//
//	
//		List<Repository> repositories = factory.getRepositories(parameter);
//		System.out.println("Id del repository "+repositories.get(0).getId());
//		org.apache.chemistry.opencmis.client.api.Session alfrescoSession = repositories.get(0).createSession();
//		Folder cvFolder = (Folder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV");
//		
//		
//		//N.B. TODO Folder cvFolder = (Folder) alfrescoService.getFolderByPath("/siti/orma-hr/documentLibrary/CV");
//		//N.B. TODO alfrescoService.getFolderByPath
//
//		if (is!=null){
//				AlfrescoFolder mainLetterFolder = null;
//				AlfrescoFolder mainRangeFolder = null;
//				AlfrescoFolder emailFolder = null;
//				AlfrescoFolder emailCVFolder = null;
//				AlfrescoFolder emailAllFolder = null;
//				String PATTERN = "^[A-Za-z]$";
//            	Pattern pattern = 
//                Pattern.compile(PATTERN);
//
//                Matcher matcher = pattern.matcher(email.substring(0,1));
//            	if (!matcher.matches()){
//                   
//					try
//					{
//						mainLetterFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro");
//						System.out.println("Cartella Altro trovata...");
//					}
//					catch(CmisObjectNotFoundException ex)
//					{
//						System.out.println("Cartella anno non trovata la creo...");
//						Map<String, Object> folderProperties = new HashMap<String, Object>();
//						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//						folderProperties.put(PropertyIds.NAME, "Altro");
//						mainLetterFolder = (AlfrescoFolder) cvFolder.createFolder(folderProperties);
//						System.out.println("Fatto");
//					}
//					try
//					{
//						emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro/"+email);
//						System.out.println("Cartella candidato trovata...");
//					}
//					catch(CmisObjectNotFoundException ex)
//					{
//						System.out.println("Cartella anno non trovata la creo...");
//						Map<String, Object> folderProperties = new HashMap<String, Object>();
//						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//						folderProperties.put(PropertyIds.NAME, email);
//						emailFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
//						System.out.println("Fatto");
//					}
//					try
//					{
//						emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro/"+email+"/CV");
//						
//					}
//					catch(CmisObjectNotFoundException ex)
//					{
//						System.out.println("Cartella CV candidato non trovata la creo...");
//						Map<String, Object> folderProperties = new HashMap<String, Object>();
//						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//						folderProperties.put(PropertyIds.NAME, "CV");
//						emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//						System.out.println("Fatto");
//					}
//					try
//					{
//						emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro/"+email+"/Allegati");
//						System.out.println("Cartella giorno trovata...");
//					}
//					catch(CmisObjectNotFoundException ex)
//					{
//						System.out.println("Cartella giorno non trovata la creo...");
//						Map<String, Object> folderProperties = new HashMap<String, Object>();
//						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//						folderProperties.put(PropertyIds.NAME, "Allegati");
//						emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//						System.out.println("Fatto");
//					}
//            	}else{
//            		try
//					{
//						mainLetterFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase());
//						System.out.println("Cartella candidato trovata...");
//					}
//					catch(CmisObjectNotFoundException ex)
//					{
//						System.out.println("Cartella anno non trovata la creo...");
//						Map<String, Object> folderProperties = new HashMap<String, Object>();
//						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//						folderProperties.put(PropertyIds.NAME, email.substring(0,1).toUpperCase());
//						mainLetterFolder = (AlfrescoFolder) cvFolder.createFolder(folderProperties);
//						System.out.println("Fatto");
//					}
//            		PATTERN = "^[A-Ma-m]$";
//                	pattern = Pattern.compile(PATTERN);
//
//                    matcher = pattern.matcher(email.substring(1,2));
//                	if (matcher.matches()){
//						try
//						{
//							mainRangeFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+
//									email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
//									email.substring(0,1).toUpperCase()+"M");
//							System.out.println("Cartella main range...");
//						}
//						catch(CmisObjectNotFoundException ex)
//						{
//							System.out.println("Cartella anno non trovata la creo...");
//							Map<String, Object> folderProperties = new HashMap<String, Object>();
//							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//							folderProperties.put(PropertyIds.NAME, email.substring(0,1).toUpperCase()+"A_"+
//									email.substring(0,1).toUpperCase()+"M");
//							mainRangeFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
//							System.out.println("Fatto");
//						}
//						try
//						{
//							emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/" +
//									email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
//									email.substring(0,1).toUpperCase()+"M/"+email);
//							System.out.println("Cartella candidato trovata...");
//						}
//						catch(CmisObjectNotFoundException ex)
//						{
//							System.out.println("Cartella anno non trovata la creo...");
//							Map<String, Object> folderProperties = new HashMap<String, Object>();
//							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//							folderProperties.put(PropertyIds.NAME, email);
//							emailFolder = (AlfrescoFolder) mainRangeFolder.createFolder(folderProperties);
//							System.out.println("Fatto");
//						}
//						try
//						{
//							emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
//									email.substring(0,1).toUpperCase()+"M/"+email+"/CV");
//							
//						}
//						catch(CmisObjectNotFoundException ex)
//						{
//							System.out.println("Cartella CV candidato non trovata la creo...");
//							Map<String, Object> folderProperties = new HashMap<String, Object>();
//							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//							folderProperties.put(PropertyIds.NAME, "CV");
//							emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//							System.out.println("Fatto");
//						}
//						try
//						{
//							emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
//									email.substring(0,1).toUpperCase()+"M/"+email+"/Allegati");
//							System.out.println("Cartella allegati trovata...");
//						}
//						catch(CmisObjectNotFoundException ex)
//						{
//							System.out.println("Cartella giorno non trovata la creo...");
//							Map<String, Object> folderProperties = new HashMap<String, Object>();
//							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//							folderProperties.put(PropertyIds.NAME, "Allegati");
//							emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//							System.out.println("Fatto");
//						}
//                	}else{
//                		PATTERN = "^[N-Zn-z]$";
//                    	pattern = Pattern.compile(PATTERN);
//
//                        matcher = pattern.matcher(email.substring(1,2));
//                    	if (matcher.matches()){
//    						try
//    						{
//    							mainRangeFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+
//    									email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
//    									email.substring(0,1).toUpperCase()+"Z");
//    							System.out.println("Cartella main range...");
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella anno non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, email.substring(0,1).toUpperCase()+"N_"+
//    									email.substring(0,1).toUpperCase()+"Z");
//    							mainRangeFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//    						try
//    						{
//    							emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/" +
//    									email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
//    									email.substring(0,1).toUpperCase()+"Z/"+email);
//    							System.out.println("Cartella candidato trovata...");
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella anno non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, email);
//    							emailFolder = (AlfrescoFolder) mainRangeFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//    						try
//    						{
//    							emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
//    									email.substring(0,1).toUpperCase()+"Z/"+email+"/CV");
//    							
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella CV candidato non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, "CV");
//    							emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//    						try
//    						{
//    							emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
//    									email.substring(0,1).toUpperCase()+"Z/"+email+"/Allegati");
//    							System.out.println("Cartella allegati trovata...");
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella giorno non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, "Allegati");
//    							emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//                		}else{
//                			try
//    						{
//    							mainRangeFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+
//    									email.substring(0,1).toUpperCase()+"/Altro");
//    							System.out.println("Cartella main range...");
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella anno non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, "Altro");
//    							mainRangeFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//                			try
//    						{
//    							emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/" +
//    									email.substring(0,1).toUpperCase()+"/Altro/"+email);
//    							System.out.println("Cartella candidato trovata...");
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella anno non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, email);
//    							emailFolder = (AlfrescoFolder) mainRangeFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//                			try
//    						{
//    							emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/Altro/"+email+"/CV");
//    							
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella CV candidato non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, "CV");
//    							emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//    						try
//    						{
//    							emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/Altro/"+email+"/Allegati");
//    							System.out.println("Cartella allegati trovata...");
//    						}
//    						catch(CmisObjectNotFoundException ex)
//    						{
//    							System.out.println("Cartella giorno non trovata la creo...");
//    							Map<String, Object> folderProperties = new HashMap<String, Object>();
//    							folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
//    							folderProperties.put(PropertyIds.NAME, "Allegati");
//    							emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
//    							System.out.println("Fatto");
//    						}
//                		}
//                		}
//                	
//                	}
//					
//					String title = "CV_"+email+"_"+opp;
//					
//					Map<String, Object> fileProperties = new HashMap<String, Object>();
//					fileProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:cm:titled");
//					fileProperties.put("cm:title", title);
//					//fileProperties.put("cm:description", "My document");
//					fileProperties.put(PropertyIds.NAME, names.get(0));
//					
//				//	MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
//	//					mimeTypesMap.addMimeTypes("application/pdf");
//	//					mimeTypesMap.addMimeTypes("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//					// only by file name
//					
//					String mimeType = determineMimeType(extensions.get(0));
//					
//					ContentStream contentStream = new ContentStreamImpl(names.get(0),new BigInteger(baoss.get(0).toByteArray()),mimeType,new ByteArrayInputStream(baoss.get(0).toByteArray()));
//					System.out.println("Carico il file...");
//			
//					Document newDoc = emailCVFolder.createDocument(fileProperties, contentStream, VersioningState.MAJOR);
////					AlfrescoDocument alfDoc = (AlfrescoDocument) newDoc;
////					alfDoc.addAspect("P:cm:titled");
////					if(alfDoc.hasAspect("P:cm:titled")) {
////						  Map<String, Object> properties = new HashMap<String, Object>();
////						  properties.put("cm:title", "Example title");
////						  alfDoc.updateProperties(properties);
////					}
//					
//					
//					
//					baoss.remove(0);
//					extensions.remove(0);
//					names.remove(0);
//					for(int i =0;i<baoss.size();i++){
//						String mimeType_i = determineMimeType(extensions.get(i));
//						title = "All_"+email+"_"+opp;
//						fileProperties = new HashMap<String, Object>();
//						fileProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:cm:titled");
//						fileProperties.put("cm:title", title);
//						fileProperties.put(PropertyIds.NAME, names.get(i));
//						ContentStream contentStream_i = new ContentStreamImpl(names.get(i),new BigInteger(baoss.get(i).toByteArray()),mimeType,new ByteArrayInputStream(baoss.get(i).toByteArray()));
//						System.out.println("Carico il file...");
//						try{
//							Document newDoc_i = emailAllFolder.createDocument(fileProperties, contentStream, VersioningState.MAJOR);
//						}catch (Exception e){
//							System.out.println("File non caricato!!!");
//						}
//						
//					}
//				
//			}
//		}
		
	

	private String determineMimeType(String extension) {
		
		String mimeType = "application/octet-stream";//mimeTypesMap.getContentType(fileName);
		if(extension.equals("pdf"))
		{
			mimeType ="application/pdf";
		}
//		else if(extension.equals("doc"))
//		{
//			mimeType ="application/vnd.openxmlformats-officedocument.wordprocessingml.document";
//		}
//		else if(extension.equals("docx"))
//		{
//			mimeType ="application/vnd.openxmlformats-officedocument.wordprocessingml.document";
//		}
		else if(extension.equals("xlsx"))
		{
			mimeType ="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
		}
		else if(extension.equals("xls"))
		{
			mimeType ="application/msexcel";
		}
		else if(extension.equals("pptx"))
		{
			mimeType ="application/vnd.openxmlformats-officedocument.presentationml.presentation";
		}
		else if(extension.equals("txt"))
		{
			mimeType ="application/text";
		}
		else if(extension.equals("doc"))
		{
			mimeType ="application/msword";
		}
		
		
		System.out.println("Tipo del file "+extension);
		return mimeType;
	}

	public List<RisultatoRicerca>  ricerca(RicercaForm ricercaForm){
		SessionFactory factory = SessionFactoryImpl.newInstance();
		
		Map<String,String> parameter = new HashMap<String, String>();
		List<RisultatoRicerca> risultati = new ArrayList<RisultatoRicerca>();
		// user credentials
		//parameter.put(SessionParameter.USER, "user");
		//parameter.put(SessionParameter.PASSWORD, "ljeq0AjF0kz36IJfXbci");
		
		parameter.put(SessionParameter.USER, "admin");
		parameter.put(SessionParameter.PASSWORD, "admin");

		// connection settings
		parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost:8080/alfresco/service/cmis");
		parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
		//parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost:3000/alfresco/cmisatom");
		//parameter.put(SessionParameter.REPOSITORY_ID, "d88d6ab2-1d08-4e49-954d-1a221532ff2f");


		List<Repository> repositories = factory.getRepositories(parameter);
		System.out.println("Id del repository "+repositories.get(0).getId());
			
		OperationContext operationContext = new OperationContextImpl();
		// SELECT SCORE() sc, D.* FROM cmis:document D WHERE
		// CONTAINS('TEXT:pro*') order by sc desc
		Session session = repositories.get(0).createSession();
		StringBuilder builder = new StringBuilder();
		StringTokenizer tokenizer = new StringTokenizer(ricercaForm.getQuery().replaceAll(" +", " ")," ");
		while (tokenizer.hasMoreTokens()){
			builder.append(" CONTAINS(D,'*"+tokenizer.nextToken().replaceAll("\\\\","\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("'","\\\\'")
					+"*') "+ricercaForm.getCriteria());
		}
		String query = builder.toString().substring(0,builder.toString().lastIndexOf(ricercaForm.getCriteria()));
				
		ItemIterable<QueryResult> results = session.query(
//				"SELECT SCORE() sc, D.* FROM cmis:document D WHERE " +
		        "SELECT SCORE() sc,  cmis:objectId , cmis:name FROM cmis:document D WHERE " +
//				"CONTAINS('PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/cm:CV/cm:"+ISO9075.encode("2013")+"/cm:giugno/cm:"+ISO9075.encode("3")+"/*\"') AND "+
				"CONTAINS('PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/cm:CV//cm:CV//.\"') AND "+
				"(".concat(
						query).concat(") order by sc desc"),
				false, operationContext);
		ricercaForm.setResultSize(new Long(results.getTotalNumItems())
				.intValue());
//		results = results.skipTo(new Long(ricercaForm.getPagina()
//				* ricercaForm.getRecordPerPagina()));
//		results = results.getPage(ricercaForm.getRecordPerPagina());
		for (QueryResult queryResult : results) {
			RisultatoRicerca r = new RisultatoRicerca(null, queryResult
					.getPropertyValueById("cmis:objectId").toString(),
					queryResult.getPropertyValueById("cmis:name").toString(),
					null);
			PropertyData scoreProperty = queryResult
					.getPropertyByQueryName("sc");
			Double score = Double.valueOf(scoreProperty.getFirstValue()
					.toString());
			r.setScore(score);
			PropertyData creationDate = queryResult
					.getPropertyById("cmis:creationDate");
			if (creationDate != null) {
				GregorianCalendar gc = (GregorianCalendar) creationDate
						.getFirstValue();
				r.setDataAggiornamento(gc.getTime());
			}
			risultati.add(r);
		}

		return risultati;
		
	}
	
	public Document ricercaDocumentoById(String id){
		SessionFactory factory = SessionFactoryImpl.newInstance();
		
		Map<String,String> parameter = new HashMap<String, String>();
		List<RisultatoRicerca> risultati = new ArrayList<RisultatoRicerca>();
		// user credentials
		parameter.put(SessionParameter.USER, "admin");
		parameter.put(SessionParameter.PASSWORD, "admin");

		// connection settings
		//parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost:8080/alfresco/service/cmis");
		parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
		parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost:8080/alfresco/cmisatom");
		parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
		//parameter.put(SessionParameter.REPOSITORY_ID, "d88d6ab2-1d08-4e49-954d-1a221532ff2f");


		List<Repository> repositories = factory.getRepositories(parameter);
		System.out.println("Id del repository "+repositories.get(0).getId());
			
		OperationContext operationContext = new OperationContextImpl();
		// SELECT SCORE() sc, D.* FROM cmis:document D WHERE
		// CONTAINS('TEXT:pro*') order by sc desc
		Session session = repositories.get(0).createSession();
		StringBuilder builder = new StringBuilder();
		
		
		//QUERY PER VARI CV
		ItemIterable<QueryResult> results = session.query(
//				"SELECT SCORE() sc, D.* FROM cmis:document D WHERE " +
		        " SELECT SCORE() sc,  D.cmis:objectId , D.cmis:name, t.cm:title FROM cmis:document as D join cm:titled as t on D.cmis:objectId = t.cmis:objectId WHERE "+ //cmis:objectId=" + id+")",
				" CONTAINS(D,'PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/cm:CV/cm:T/cm:TA_TM/cm:"+ISO9075.encode("tartatommy@libero.it")+"/cm:CV//.\"')",
				false, operationContext);
		
		//QUERY PER ID
//		ItemIterable<QueryResult> results = session.query(
////				"SELECT SCORE() sc, D.* FROM cmis:document D WHERE " +
//		        " SELECT SCORE() sc,  D.* , t.cm:title FROM cmis:document as D join cm:titled as t on D.cmis:objectId = t.cmis:objectId WHERE D.cmis:objectId='"+id+"'",
////				" CONTAINS(D,'PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/cm:CV/cm:T/cm:TA_TM/cm:"+ISO9075.encode("tartatommy@libero.it")+"/cm:CV//.\"')",
//				false, operationContext);
		
		//Document document = (Document) session.getObject(id);


		for (QueryResult queryResult : results) {
			RisultatoRicerca r = new RisultatoRicerca(null, queryResult
					.getPropertyValueById("cmis:objectId").toString(),
					queryResult.getPropertyValueById("cmis:name").toString(),
					null);
			System.out.println(queryResult.getPropertyValueById("cmis:name"));
			System.out.println(queryResult.getPropertyValueById("cm:title"));
			System.out.println(queryResult.getPropertyValueById("cmis:objectId"));
			PropertyData scoreProperty = queryResult
					.getPropertyByQueryName("sc");
			Double score = Double.valueOf(scoreProperty.getFirstValue()
					.toString());
			r.setScore(score);
			PropertyData creationDate = queryResult
					.getPropertyById("cmis:creationDate");
			if (creationDate != null) {
				GregorianCalendar gc = (GregorianCalendar) creationDate
						.getFirstValue();
				r.setDataAggiornamento(gc.getTime());
			}
			risultati.add(r);
		}

		//return null;
		return null;
	}
	
	  public static String formatMonth(int month, Locale locale) {
		    DateFormat formatter = new SimpleDateFormat("MMMMM", locale);
		    GregorianCalendar calendar = new GregorianCalendar();
		    calendar.set(Calendar.MONTH, month);
		    return formatter.format(calendar.getTime());
		}
	  
	  public static void main(String args[]) throws IOException{
		  EmailTask rmt= new EmailTask();
		  //rmt.fetchOldMail();
		  
		  //QUERY DOCUMENT/DOCUMENTS
		  RicercaForm rForm = new RicercaForm();
		  rForm.setQuery("BLAZAR");
		  rForm.setCriteria("AND");
		  rForm.setRecordPerPagina(10);
		  rForm.setPagina(0);
		  List<RisultatoRicerca>risultati= rmt.ricerca(rForm);
		  System.out.println(risultati.size());
		  Document doc = rmt.ricercaDocumentoById("workspace://SpacesStore/7b376638-b901-40c9-8337-53ebf5dd7f39;1.0");
	
		  FileOutputStream fos = new FileOutputStream(new File("C://allegati//"+doc.getContentStreamFileName()));
     	  IOUtils.copy(doc.getContentStream().getStream(),fos);
	      fos.close();
	      
	      //STORE
//		  FileInputStream fis = new FileInputStream(new File("C://allegati//CV_tartatommy@libero.it_T2000.doc"));
//		  ByteArrayOutputStream baos = new ByteArrayOutputStream();
//          byte[] buffer = new byte[4096];
//          int byteRead;
//          while ((byteRead = fis.read(buffer)) != -1) {
//              baos.write(buffer, 0, byteRead);
//          }
//		  fis.close();
//		  baos.close();
//		  ArrayList<String> ext = new ArrayList<String>();
//		  ArrayList<String> names = new ArrayList<String>();
//		  ArrayList<ByteArrayOutputStream> baoss = new ArrayList<ByteArrayOutputStream>();
//		  baoss.add(baos);
//		  ext.add("doc");
//		  names.add("CV_tommaso_formica.doc");
//		  rmt.storeCV(fis,"T20000","tartatommy@libero.it",ext,names,baoss);
		  
	      System.out.println("FINITO");	  
	  }

	public void printSth() {
		System.out.println("doing something:"+getMessageWindow());
		
	}
	
	 public Boolean saveAll(SchedaCandidato schedaCandidato, MultipartFile multipartFile) {
			
		 DatiGenerali dg = ricercaRepository.caricaDatiGenerali(schedaCandidato);
		    try {
		    	String name = multipartFile.getOriginalFilename();
		    	String email = dg.getMail1();
		    	String extension = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);
		    	
		    	CVCandidato ultimoAll = ricercaRepository.caricaUltimoDocumento(schedaCandidato.getIdSchedaCandidato(), "All");
		    	Integer nextIndex = 1;
		    	if (ultimoAll!=null){
		    		nextIndex = Integer.parseInt(ultimoAll.getTitolo().substring(ultimoAll.getTitolo().lastIndexOf("_")+1))+1;
		    	}		    			    	
		    	String title = "All_"+email+"_"+nextIndex; 
		    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
                baos.write(multipartFile.getBytes());		       
		        String alfrescoId  = alfrescoService.storeCV(email, extension, name, title, baos,"All");
		        CVCandidato doc = new CVCandidato();
		        doc.setDataRicezione(new Date());
		        doc.setIdAlfresco(alfrescoId);
		        doc.setIdCandidato(schedaCandidato.getIdSchedaCandidato());
		        doc.setNome(name);
		        doc.setEstensione(extension);
		        doc.setTipo("All");
		        doc.setTitolo(title);
		        candidatoRepository.salvaLinkAlfresco(doc);
		        return true;
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		    return true;

		}
	 
	 public Boolean saveCV(SchedaCandidato schedaCandidato, MultipartFile multipartFile) {
			
		DatiGenerali dg = ricercaRepository.caricaDatiGenerali(schedaCandidato);
		
		Boolean check = false;
	    try {
			
	    	check=ricercaRepository.checkNomeDocumento(multipartFile.getOriginalFilename(), schedaCandidato.getIdSchedaCandidato());
			
	    	String name = multipartFile.getOriginalFilename();
	    	String email = dg.getMail1();
	    	String extension = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);
	    			    	
	    	CVCandidato ultimoAll = ricercaRepository.caricaUltimoDocumento(schedaCandidato.getIdSchedaCandidato(), "CV");
	    	Integer nextIndex = 1;
	    	if (ultimoAll!=null){
	    		nextIndex = Integer.parseInt(ultimoAll.getTitolo().substring(ultimoAll.getTitolo().lastIndexOf("_")+1))+1;
	    	}
	    	String title = "CV_"+email+"_"+(nextIndex); 
	    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos.write(multipartFile.getBytes());		       
	        String alfrescoId  = alfrescoService.storeCV(email, extension, name, title, baos,"CV");
	        CVCandidato doc = new CVCandidato();
	        doc.setDataRicezione(new Date());
	        doc.setIdAlfresco(alfrescoId);
	        doc.setIdCandidato(schedaCandidato.getIdSchedaCandidato());
	        doc.setNome(name);
	        doc.setEstensione(extension);
	        doc.setTipo("CV");
	        doc.setTitolo(title);
	        candidatoRepository.salvaLinkAlfresco(doc);
	        return true;
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return true;

	}

}
